package com.darrenchan.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Desc
 * @Author chenchi03
 * @CreateTime 2019-12-10 17:43
 */
public class QLint89 {
    public int kSum(int[] nums, int k, int target) {
        List<List<Integer>> results = new ArrayList<>();
        if (nums == null) {
            return results.size();
        }

        if (nums.length == 0) {
            results.add(new ArrayList<>());
            return results.size();
        }

        Arrays.sort(nums);
        dfs(nums, 0, new ArrayList<>(), results, k, target);

        return results.size();
    }

    private void dfs(int[] nums, int index, List<Integer> subsets, List<List<Integer>> results, int k, int target) {
        if (k == 0 && target == 0) {
            results.add(new ArrayList<>(subsets));
        }

        for (int i = index; i < nums.length; i++) {
            if (target < nums[i]) {
                break;
            }
            subsets.add(nums[i]);
            dfs(nums, i + 1, subsets, results, k - 1, target - nums[i]);
            subsets.remove(subsets.size() - 1);
        }
    }
}
